#include "els.h"

#include "els_heap.h"
#include "els_func.h"
#include "els_gc.h"
#include "els_mem.h"
#include "els_object.h"
#include "els_vmhost.h"
#include "els_string.h"
#include "els_unit.h"

#define MINBUFFER	256
#define strmark(s)    {if ((s)->marked == 0) (s)->marked = 1;}
#define VALIDLINK(L, st,n)      (NONEXT <= (st) && (st) < (n))

typedef struct GcObj {
  Hash *tmark;  
  ElsCfunc *cmark;  
} GcObj;

static void markobject (GcObj *st, StackObj *o);

static void codeirmark (els_ir_code *f) {
  if (!f->marked) {
    int i;
    f->marked = 1;
    strmark(f->source);
    for (i=0; i<f->nkstr; i++)
      strmark(f->kstr[i]);
    for (i=0; i<f->nkcodeir; i++)
      codeirmark(f->kcodeir[i]);
    for (i=0; i<f->nlocvars; i++)  
      strmark(f->locvars[i].varname);
  }
}

static void markstack (els_VmObj *L, GcObj *st) {
  Els_vminline_obj o;
  for (o=L->stack; o<L->top; o++)
    markobject(st, o);
}

static void marklock (els_VmObj *L, GcObj *st) {
  int i;
  for (i=0; i<L->refSize; i++) {
    if (L->refArray[i].st == LOCK)
      markobject(st, &L->refArray[i].o);
  }
}

static void mark_csfunciotn (GcObj *st, ElsCfunc *cl) {
  if (!ismarked(cl)) {
    if (!cl->isC)
      codeirmark(cl->f.l);
    cl->mark = st->cmark;  
    st->cmark = cl;
  }
}

static void marktagmethods (els_VmObj *L, GcObj *st) {
  int e;
  for (e=0; e<TM_N; e++) {
    int t;
    for (t=0; t<=L->last_tag; t++) {
      ElsCfunc *cl = els_unit_gettm(L, t, e);
      if (cl) mark_csfunciotn(st, cl);
    }
  }
}

static void markobject (GcObj *st, StackObj *o) {
  switch (ttype(o)) {
    case ELS_TYPE_USERDATA:  case ELS_TYPE_STRING:
      strmark(tsvalue(o));
      break;
    case ELS_TYPE_MARK:
      mark_csfunciotn(st, infovalue(o)->func);
      break;
    case ELS_TYPE_FUNCTION:
      mark_csfunciotn(st, clvalue(o));
      break;
    case ELS_TYPE_UNIT: {
      if (!ismarked(hvalue(o))) {
        hvalue(o)->mark = st->tmark;  
        st->tmark = hvalue(o);
      }
      break;
    }
    default: break;  
  }
}

static void markall (els_VmObj *L) {
  GcObj st;
  st.cmark = NULL;
  st.tmark = L->gt;  
  L->gt->mark = NULL;
  marktagmethods(L, &st);  
  markstack(L, &st); 
  marklock(L, &st); 
  while(1) {  
    if (st.cmark) {
      int i;
      ElsCfunc *f = st.cmark;  
      st.cmark = f->mark;  
      for (i=0; i<f->nupvalues; i++)  
        markobject(&st, &f->upvalue[i]);
    }
    else if (st.tmark) {
      int i;
      Hash *h = st.tmark;  
      st.tmark = h->mark;  
      for (i=0; i<h->size; i++) {
        Node *n = node(h, i);
        if (ttype(key(n)) != ELS_TYPE_NULL) {
          if (ttype(val(n)) == ELS_TYPE_NULL)
            els_Unit_remove(h, key(n));  
          markobject(&st, &n->key);
          markobject(&st, &n->val);
        }
      }
    }
    else break;  
  }
}

static int hasmark (const StackObj *o) {
  
  switch (o->ttype) {
    case ELS_TYPE_STRING: case ELS_TYPE_USERDATA:
      return tsvalue(o)->marked;
    case ELS_TYPE_UNIT:
      return ismarked(hvalue(o));
    case ELS_TYPE_FUNCTION:
      return ismarked(clvalue(o));
    default:  
      return 1;
  }
}

static void invalidaterefs (els_VmObj *L) {
  int n = L->refSize;
  int i;
  for (i=0; i<n; i++) {
    struct Ref *r = &L->refArray[i];
    if (r->st == HOLD && !hasmark(&r->o))
      r->st = COLLECTED;
  }
}

static void collectcodeir (els_VmObj *L) {
  els_ir_code **p = &L->rootcodeir;
  els_ir_code *next;
  while ((next = *p) != NULL) {
    if (next->marked) {
      next->marked = 0;
      p = &next->next;
    }
    else {
      *p = next->next;
      els_Function_freecodeir(L, next);
    }
  }
}

static void collect_csfunciotn (els_VmObj *L) {
  ElsCfunc **p = &L->rootcl;
  ElsCfunc *next;
  while ((next = *p) != NULL) {
    if (ismarked(next)) {
      next->mark = next;  
      p = &next->next;
    }
    else {
      *p = next->next;
      els_Function_free_csfunciotn(L, next);
    }
  }
}

static void collectunit (els_VmObj *L) {
  Hash **p = &L->rootunit;
  Hash *next;
  while ((next = *p) != NULL) {
    if (ismarked(next)) {
      next->mark = next;  
      p = &next->next;
    }
    else {
      *p = next->next;
      els_Unit_free(L, next);
    }
  }
}

static void checkunit (els_VmObj *L, stringunit *tb) {
  if (tb->nuse < (lint32)(tb->size/4) && tb->size > 10)
    els_string_resize(L, tb, tb->size/2);  
}

static void collectstrings (els_VmObj *L, int all) {
  int i;
  for (i=0; i<L->strt.size; i++) {  
    TString **p = &L->strt.hash[i];
    TString *next;
    while ((next = *p) != NULL) {
      if (next->marked && !all) {  
        if (next->marked < FIXMARK)  
          next->marked = 0;
        p = &next->nexthash;
      } 
      else {  
        *p = next->nexthash;
        L->strt.nuse--;
        L->nblocks -= sizestring(next->len);
        els_Mem_free(L, next);
      }
    }
  }
  checkunit(L, &L->strt);
}

static void collectudata (els_VmObj *L, int all) {
  int i;
  for (i=0; i<L->udt.size; i++) {  
    TString **p = &L->udt.hash[i];
    TString *next;
    while ((next = *p) != NULL) {
      if (next->marked && !all) {  
        next->marked = 0;
        p = &next->nexthash;
      } 
      else {  
        int tag = next->u.d.tag;
        *p = next->nexthash;
        next->nexthash = L->UNITSEC[tag].collected;  
        L->UNITSEC[tag].collected = next;
        L->nblocks -= sizestring(next->len);
        L->udt.nuse--;
      }
    }
  }
  checkunit(L, &L->udt);
}

static void checkMbuffer (els_VmObj *L) {
  if (L->Mbuffsize > MINBUFFER*2) {  
    size_t newsize = L->Mbuffsize/2;  
    L->nblocks += (newsize - L->Mbuffsize)*sizeof(char);
    L->Mbuffsize = newsize;
    els_Mem_reallocvector(L, L->Mbuffer, newsize, char);
  }
}

static void callgcTM (els_VmObj *L, const StackObj *o) {
  ElsCfunc *tm = els_unit_gettmbyObj(L, o, TM_GC);
  if (tm != NULL) {
    int oldah = L->allowhooks;
    L->allowhooks = 0;  
    els_Heap_checkstack(L, 2);
    clvalue(L->top) = tm;
    ttype(L->top) = ELS_TYPE_FUNCTION;
    *(L->top+1) = *o;
    L->top += 2;
    els_Heap_call(L, L->top-2, 0);
    L->allowhooks = oldah;  
  }
}

static void els_Gc_collectgarbage (els_VmObj *L) {
  markall(L);
  invalidaterefs(L);  
  els_Gc_collect(L, 0);
  checkMbuffer(L);
  L->GCthreshold = 2*L->nblocks;  
  callgcTM(L, &els_Object_nullobject);
}

static void callgcTMudata (els_VmObj *L) {
  int tag;
  StackObj o;
  ttype(&o) = ELS_TYPE_USERDATA;
  L->GCthreshold = 2*L->nblocks;  
  for (tag=L->last_tag; tag>=0; tag--) {  
    TString *udata;
    while ((udata = L->UNITSEC[tag].collected) != NULL) {
      L->UNITSEC[tag].collected = udata->nexthash;  
      tsvalue(&o) = udata;
      callgcTM(L, &o);
      els_Mem_free(L, udata);
    }
  }
}

void els_Gc_collect (els_VmObj *L, int all) {
  collectudata(L, all);
  callgcTMudata(L);
  collectstrings(L, all);
  collectunit(L);
  collectcodeir(L);
  collect_csfunciotn(L);
}

void els_Gc_checkGC (els_VmObj *L) {
  if (L->nblocks >= L->GCthreshold)
    els_Gc_collectgarbage(L);
}

